package com.poetry.vup.user.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.poetry.vup.common.entity.user.VupUserInfoDO;
import com.poetry.vup.common.exception.KabobExceptionUtil;
import com.poetry.vup.common.result.BaseResult;
import com.poetry.vup.common.result.ResultCode;
import com.poetry.vup.common.util.JacksonUtil;
import com.poetry.vup.common.util.OSSClientUtil;
import com.poetry.vup.user.domain.VupUserInfoDTO;
import com.poetry.vup.user.domain.query.Persona;
import com.poetry.vup.user.service.VupUserInfoService;
import com.poetry.vup.works.service.VupExhibitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/userInfo")
public class VupUserInfoController {

    @Autowired
    private VupUserInfoService vupUserInfoService;

    @Autowired
    private VupExhibitionService vupExhibitionService;

    @Autowired
    private OSSClientUtil ossClientUtil;

    /**
     * 同步个人信息
     */
    @RequestMapping("/syncUserInfo")
    public BaseResult syncUserInfo(@RequestParam("midId") String midId,@RequestParam("userId") Long userId){
        BaseResult baseResult = BaseResult.failed("添加失败");
        if(StringUtils.isBlank(midId) || userId == null){
            return BaseResult.failed("输入参数不全，请检查");
        }
        String url = "https://api.bilibili.com/x/space/acc/info?mid="+midId;

        try {
            HttpResponse httpResponse = HttpRequest.get(url).execute();
            String body = httpResponse.body();
            /*OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient.newCall(request).execute();*/
            //if(response.isSuccessful()){
                //String body = response.body().string();
                JSONObject jsonObject = JSON.parseObject(body);
                JSONObject jsonData = (JSONObject) jsonObject.get("data");

                //获取个人介绍
                String sign = (String) jsonData.get("sign");
                //获取名称
                String name = (String) jsonData.get("name");
                //获取头像
                String face =ossClientUtil.getUrl(ossClientUtil.uploadImg2Oss((String) jsonData.get("face")));
                //获取封面图和图标
                JSONObject json = (JSONObject) jsonData.get("live_room");
                String liveUrl = null;
                if(json!=null){
                    String cover = (String) json.get("cover");
                    if(StringUtils.isNotBlank(cover)){

                    }
                    liveUrl = (String) json.get("url");

                }

                //更新用户的个人信息
                VupUserInfoDO vupUserInfoDO = vupUserInfoService.findById(userId);
                if(vupUserInfoDO != null){
                    vupUserInfoDO.setHeadUrl(face);
                    vupUserInfoDO.setId(userId);
                    vupUserInfoDO.setNickName(name);
                    vupUserInfoDO.setPersonalSign(sign);
                    vupUserInfoDO.setMidId(midId);
                    vupUserInfoDO.setLiveUrl(liveUrl);
                    int i = vupUserInfoService.update(JacksonUtil.objectToObject(vupUserInfoDO, VupUserInfoDTO.class));
                    if(i>0){
                        baseResult = BaseResult.success(vupUserInfoDO);
                    }

                }else{
                    baseResult = BaseResult.failed("信息已同步");
                }

            //}

        }catch (Exception e){
            KabobExceptionUtil.throwError(ResultCode.FAILED,"操作失败",e);
        }
        return baseResult;
    }

    /**
     * 获取个人信息
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    public BaseResult getUserInfo(@RequestParam("userId") Long userId, HttpServletRequest request){
        if(userId == null){
            return BaseResult.failed("输入参数不全，请检查");
        }
        return vupUserInfoService.getUserInfo(userId);
    }

    /**
     * 上传形象图片
     */
    @RequestMapping(value = "/uploadUserImage",method = RequestMethod.GET)
    public BaseResult uploadUserImage(@RequestParam("userId") Long userId,
                                      @RequestParam("file")MultipartFile file){
        BaseResult baseResult = BaseResult.failed("");
        Long id = vupUserInfoService.uploadUserImage(userId,file);
        if (id>0){
            baseResult = BaseResult.success(id);
        }else{
            baseResult = BaseResult.failed("上传失败");
        }
        return baseResult;
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/updateUser")
    public BaseResult updateUser(@RequestParam("perIntroduction") String perIntroduction,@RequestParam("id") Long id){
        BaseResult<Object> baseResult = BaseResult.failed("更新失败");
        VupUserInfoDO vupUserInfoDO = vupUserInfoService.findById(id);
        if (vupUserInfoDO != null){
            vupUserInfoDO.setPersonalIntroduction(perIntroduction);
            int update = vupUserInfoService.update(JacksonUtil.objectToObject(vupUserInfoDO,VupUserInfoDTO.class));
            if(update > 0){
                baseResult = BaseResult.success(update);
            }
        }

        return baseResult;
    }

    /**
     * 添加人设信息
     */
    @RequestMapping(value = "/addPersona",method = RequestMethod.POST)
    @ResponseBody
    public BaseResult addPersona(@RequestBody Persona persona){
        BaseResult baseResult = BaseResult.failed("");
        //先查询该登录用户是否是该详情页的本人
        VupUserInfoDO vupUserInfoDO = vupUserInfoService.findById(persona.getUserId());
        if(!vupUserInfoDO.getMidId().equals(persona.getMidId())){
            return BaseResult.failed("请本人添加人设信息");
        }
        Long aLong = vupUserInfoService.addPersona(persona);
        if(aLong > 0 ){
            baseResult = BaseResult.success(aLong);
        }
        return baseResult;
    }

}
